package com.liubujun.nio;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: liubujun
 * @Date: 2022/2/14 21:49
 */


public class BufferDemo1 {

    public static void main(String[] args) throws Exception {
        //创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("C:\\Users\\LiuBuJun\\Desktop\\liubujun\\01.txt","rw");
        FileChannel channel = accessFile.getChannel();

        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //读取数据到buffer中
        int bytesRead = channel.read(buffer);
        // bytesRead = -1 表示到达文件末尾
        while (bytesRead != -1 ) {
            //将数据从buffer取出来 .flip()反转读写模式
            buffer.flip();

            while (buffer.hasRemaining()) {
                System.out.println((char)buffer.get());
            }
            //清除缓存区内容
            buffer.clear();
            bytesRead =  channel.read(buffer);
        }
        accessFile.close();
        System.out.println("over");
    }
}
